package cn.jdy.plugins.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.plugins.entity.Website;
import cn.jdy.plugins.service.WebsiteService;

/**
 * 网站基本信息管理
 *
 * 
 */
@Controller
@RequestMapping("/website")
public class WebsiteCtrl extends BaseCtrl {
	@Autowired
	private WebsiteService websiteService;

	
	@RequestMapping("/index")
	public ModelAndView add() {
		List<Website> listwebsite=websiteService.findAll();
		if(listwebsite!=null && listwebsite.size()>0){
			return edit(listwebsite.get(0).getId());
		}else{
			return new ModelAndView("/website/website.jsp");
		}
	}
	
	
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable String id) {
		ModelAndView mv = new ModelAndView();
		Website website = this.websiteService.find(id);
		if(website != null) {
			mv.setViewName("/website/website.jsp");
			mv.addObject("data", website);
		}
		return mv;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(Website entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(entity.getId() == null || entity.getId().length()==0) {
				entity.setId(null);
				this.websiteService.save(entity);
			}else{
			  this.websiteService.updateWithValidator(entity);
			}
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "网站基本信息更新异常！", e);
		}
		return jsonMap;
	}

	
	 /**
   * 异步添加带查询
   * @param sp
   * @param fromDate
   * @param toDate
   * @return
   */
  @RequestMapping("/queryBySum")
  @ResponseBody
  public Map<String, Object> queryByPage(String type){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      List<Website> listwebsite=websiteService.findAll();
   
      Website sps=listwebsite.get(0);
      int i=sps.getDaysum()==null?0:sps.getDaysum();
      sps.setDaysum(i+1);
      int j=sps.getTotalsum()==null?0:sps.getTotalsum();
      sps.setTotalsum(sps.getDaysum()+j);
      /*
       *     Date now = new Date(); 
      SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
      String hehe = dateFormat.format( now ); 
       * */ 
      if ( type.equals("0")){
        websiteService.update(sps);
      }
    
      
      jsonMap.put("data", sps);

    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询异常", e);
    }
    return jsonMap;
  }
}